package vip.indo.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import vip.indo.common.JsonResult;
import vip.indo.exception.BusinessErrorException;

/**
 * @Author: tianlianyin
 * @Date: 2024/11/28 10:40
 * @Descripition:
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理参数缺失异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public JsonResult handleHttpMessageNoReadableException(MissingServletRequestParameterException ex){
        log.error("缺少请求参数，{}",ex.getMessage());
        return JsonResult.error("400","缺少请求参数");
    }

    /**
     * 空指针异常
     * @param ex 异常
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleTypeMismatchException(NullPointerException ex){
        log.error("空指针异常，{}",ex.getMessage());
        return JsonResult.error("500","空指针异常");
    }

    /**
     * 服务器异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleUnexceptedServer(Exception e){
        log.error("服务器异常，{}",e.getMessage());
        return JsonResult.error("500","服务器异常");
    }

    /**
     * 拦截业务异常，返回错误码和错误信息
     * @param e 业务异常
     * @return
     */
    @ExceptionHandler(BusinessErrorException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public JsonResult handleBusinessError(BusinessErrorException e){
        String code=e.getCode();
        String msg=e.getMsg();
        return JsonResult.error(code,msg);
    }
}
